import React, {PureComponent} from "react";
import {flushSync} from 'react-dom';
import PropTypes from 'prop-types';
import ThemeContext from "./context/theme-context";
import {Home} from "./Home";
import UserContext from "./context/user-context";

class HelloWorld extends PureComponent {
    constructor(props) {
        super(props);
        console.log('constructor被执行')
        this.state = {
            message: 'hello world'
        }
    }

    changeText() {
        setTimeout(() => {
            // 这样就实现了react18之前非react事件中同步执行的效果
            flushSync(() => {
                this.setState({
                    message: 'hello react'
                })
            })
            // render()->打印hello react
            console.log(this.state.message)
        }, 0)
    }

    addCount(num) {
        this.props.addClick(num)
    }

    // 这个render渲染函数是HelloWorld组件的
    render() {
        const {message} = this.state;
        const {text} = this.props;
        console.log(this.context);
        console.log('组件被渲染')
        return (
            <div>
                <h1>{message + ' ' + text}</h1>
                <button onClick={() => this.changeText()}>修改文本</button>
                <button onClick={() => this.addCount(1)}>+1</button>
                <button onClick={() => this.addCount(-1)}>-1</button>
                <UserContext.Consumer>
                    {/*这个是指定Context是谁*/}
                    {
                        (value) => {
                            return <span>{value.userName}</span>
                        }
                    }
                </UserContext.Consumer>
                <Home/>
            </div>
        )
    }

    componentDidMount() {
        console.log('组件被挂载完毕')
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        // snapshot即getSnapshotBeforeUpdate返回的
        console.log('组件更新完毕', prevProps, prevState, snapshot)
    }

    componentWillUnmount() {
        console.log('组件即将卸载')
    }

    // 不常用生命周期
    // shouldComponentUpdate(nextProps, nextState, nextContext) {
    //     console.log('shouldComponentUpdate');
    //     // 返回值决定是否更新（返回false不会执行渲染函数）
    //     return true;
    // }

    getSnapshotBeforeUpdate(prevProps, prevState) {
        console.log('getSnapshotBeforeUpdate')
        return {
            useScroll: 1000,
        }
    }
}

// 限制props类型
HelloWorld.propTypes = {
    text: PropTypes.string,
    addClick: PropTypes.func,
}

// 设定props默认值
HelloWorld.defaultProps = {
    text: 'bbq',
    addClick: () => {
    },
}

// 这个是给组件指定this绑定的context是谁
HelloWorld.contextType = ThemeContext;
export default HelloWorld;